<template>
    <div>
        <!-- 竞赛列表 -->
        <el-table :data="competitions" style="width: 100%">
            <!-- 竞赛列 -->
            <el-table-column prop="id" label="ID" width="100" />
            <el-table-column prop="title" label="标题" width="200" />
            <el-table-column prop="organizer" label="主办方" width="200" />
            <el-table-column prop="websiteUrl" label="官网地址" width="200" />
            <el-table-column
                prop="registrationStartTime"
                label="报名开始时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column
                prop="registrationEndTime"
                label="报名结束时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column
                prop="competitionStartTime"
                label="比赛开始时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column
                prop="competitionEndTime"
                label="比赛结束时间"
                width="200"
                :formatter="formatDate"
            />

            <el-table-column
                prop="createdAt"
                label="创建时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column
                prop="updatedAt"
                label="更新时间"
                width="200"
                :formatter="formatDate"
            />
            <el-table-column prop="category" label="类别" width="150" />
            <el-table-column prop="subCategory" label="具体下分类别" width="150" />
            <el-table-column prop="employeeNumber" label="添加人工号" width="150" />

            <!-- 图片列 -->
            <el-table-column label="图片" width="200">
                <template v-slot="scope">
                    <img
                        v-if="scope.row.imageUrl"
                        :src="scope.row.imageUrl"
                        width="100"
                        height="100"
                        alt="竞赛图片"
                    />
                    <span v-else>无图片</span>
                </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作" width="200">
                <template v-slot="scope">
                    <el-button type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" @click="deleteCompetition(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
            @current-change="handlePageChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="total, prev, pager, next, jumper"
        ></el-pagination>

        <!-- 编辑竞赛对话框 -->
        <el-dialog title="编辑竞赛" v-model="editDialogVisible">
            <el-form :model="selectedCompetition" label-width="120px">
                <el-form-item label="标题">
                    <el-input v-model="selectedCompetition.title"></el-input>
                </el-form-item>
                <el-form-item label="主办方">
                    <el-input v-model="selectedCompetition.organizer"></el-input>
                </el-form-item>
                <el-form-item label="报名开始时间">
                    <el-date-picker v-model="selectedCompetition.registrationStartTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="报名结束时间">
                    <el-date-picker v-model="selectedCompetition.registrationEndTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="比赛开始时间">
                    <el-date-picker v-model="selectedCompetition.competitionStartTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="比赛结束时间">
                    <el-date-picker v-model="selectedCompetition.competitionEndTime" type="datetime" placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="类别">
                    <el-input v-model="selectedCompetition.category" disabled></el-input>
                </el-form-item>
                <el-form-item label="具体下分类别">
                    <el-input v-model="selectedCompetition.subCategory"></el-input>
                </el-form-item>
                <el-form-item label="添加人工号">
                    <el-input v-model="selectedCompetition.employeeNumber"></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <!-- 图片上传组件 -->
                    <el-upload
                        :before-upload="handleBeforeUpload"
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError"
                        :show-file-list="false"
                    >
                        <el-button type="primary">上传图片</el-button>
                    </el-upload>
                    <!-- 显示当前图片 -->
                    <img :src="imageUrl" width="200" height="200" alt="竞赛图片" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="updateCompetition">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import service from "@/utils/request";
import { ElMessage, ElMessageBox } from 'element-plus';

// 竞赛数据
const competitions = ref([]);

// 分页相关变量
const currentPage = ref(1); // 当前页码
const pageSize = ref(10);   // 每页大小
const total = ref(0);       // 总记录数

// 编辑对话框显示状态
const editDialogVisible = ref(false);

// 当前选中的竞赛
const selectedCompetition = ref({});

// 临时图片URL
const imageUrl = ref('');

/**
 * 格式化日期函数
 * @param {Object} row - 表格行数据
 * @param {Object} column - 表格列数据
 * @param {string|Array} cellValue - 单元格值
 * @returns {string} 格式化后的日期字符串
 */
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return ''; // 如果时间为空，返回空字符串

    const date = new Date(cellValue);
    if (isNaN(date.getTime())) {
        console.error(`Invalid date value: ${cellValue}`);
        return 'Invalid Date';
    }

    const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
    };
    return new Intl.DateTimeFormat('zh-CN', options).format(date).replace(/\//g, '/');
};

/**
 * 图片上传前的处理
 * @param {File} file - 上传的文件
 * @returns {boolean} 是否阻止默认上传行为
 */
const handleBeforeUpload = (file) => {
    const formData = new FormData();
    formData.append('file', file);

    service.post('/upload/image', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
        .then(response => {
            handleUploadSuccess(response.data);
            console.log('图片上传成功，路径为:', response.data);
        })
        .catch(error => {
            handleUploadError(error);
        });

    return false; // 阻止默认上传行为
};

/**
 * 图片上传成功
 * @param {string} response - 图片路径
 */
const handleUploadSuccess = (response) => {
    if (response) {
        selectedCompetition.value.photoUrl = response;
        console.log('图片上传成功，路径为:', selectedCompetition.value.photoUrl);
        loadImage(selectedCompetition.value.photoUrl);
    }
};

/**
 * 图片上传失败
 * @param {Error} error - 错误信息
 */
const handleUploadError = (error) => {
    console.error('图片上传失败', error);
    ElMessage.error('图片上传失败，请重试');
};

/**
 * 获取竞赛数据（分页）
 */
const fetchCompetitions = async () => {
    try {
        const response = await service.get('/admin/competition/competitionsPage', {
            params: {
                page: currentPage.value, // 后端页码从 1 开始
                size: pageSize.value
            }
        });
        const data = response.data; // 分页数据
        total.value = data.total; // 总记录数
        competitions.value = data.list; // 当前页的数据列表

        // 遍历竞赛数据，加载图片
        for (const competition of competitions.value) {
            if (competition.photoUrl) {
                competition.imageUrl = await loadImage1(competition.photoUrl);
                console.log('加载图片成功:', competition.imageUrl);
            } else {
                competition.imageUrl = '';
            }
        }
    } catch (error) {
        console.error('获取竞赛数据失败', error);
    }
};

/**
 * 处理分页变化
 */
const handlePageChange = (page) => {
    currentPage.value = page;
    fetchCompetitions();
};

/**
 * 显示编辑对话框
 * @param {Object} competition - 当前选中的竞赛
 */
const showEditDialog = (competition) => {
    console.log('显示编辑对话框1:', competition.photoUrl);

    selectedCompetition.value = { ...competition };
    loadImage(competition.photoUrl);
    editDialogVisible.value = true;

    if (selectedCompetition.value.photoUrl) {
        imageUrl.value = selectedCompetition.value.photoUrl;
    } else {
        imageUrl.value = '';
    }
};

/**
 * 更新竞赛信息
 */
const updateCompetition = async () => {
    try {
        await service.put('/admin/competition/update', selectedCompetition.value);
        await fetchCompetitions();
        editDialogVisible.value = false;
        ElMessage.success('竞赛信息更新成功');
    } catch (error) {
        console.error('更新竞赛信息失败', error);
        ElMessage.error('竞赛信息更新失败');
    }
};

/**
 * 删除竞赛
 * @param {number} id - 竞赛 ID
 */
const deleteCompetition = async (id) => {
    try {
        await ElMessageBox.confirm('确定删除该竞赛吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await service.delete(`/admin/competition/${id}`);
        await fetchCompetitions();
        ElMessage.success('竞赛删除成功');
    } catch (error) {
        console.error('删除竞赛失败', error);
        ElMessage.error('竞赛删除失败');
    }
};

/**
 * 加载图片
 * @param {string} imagePath - 图片路径
 */
const loadImage = (imagePath) => {
    console.log('加载图片:', imagePath);

    service.get(`/images/${imagePath}`, {
        responseType: 'blob'
    })
        .then(response => {
            imageUrl.value = URL.createObjectURL(response.data);
            console.log('加载图片 URL:', imageUrl.value);
        })
        .catch(error => {
            console.error('图片加载失败', error);
            ElMessage.error('图片加载失败，请重试');
        });
};

/**
 * 异步加载图片
 * @param {string} imagePath - 图片路径
 * @returns {Promise<string>} 图片 URL
 */
const loadImage1 = async (imagePath) => {
    console.log('加载图片:', imagePath);

    try {
        const response = await service.get(`/images/${imagePath}`, {
            responseType: 'blob'
        });
        const imageUrl = URL.createObjectURL(response.data);
        console.log('加载图片成功，URL:', imageUrl);
        return imageUrl;
    } catch (error) {
        console.error('图片加载失败', error);
        ElMessage.error('图片加载失败，请重试');
        return '';
    }
};

// 组件挂载时获取竞赛数据
onMounted(() => {
    fetchCompetitions();
});
</script>